#!/bin/bash
# 重启所有服务 
# author    : guyadong
# date      : 2019/09/07

sh_folder=$(dirname $(readlink -f $0))
cd $sh_folder

# 脚本初始化
. ./common_init.sh

# 显示命令行参数说明
usage() {
    echo "重启所有facelog相关服务"
    echo "Usage:"
    echo "  service_restart.sh [OPTION]... "
    echo "OPTION:"
    echo "    -a --all 重启所有基础服务(mysql,redis,nginx)，默认不执行"
    echo "    -w --wait 等待所有服务端口可用，默认不等待"
    echo "    -s --stop 只停止服务"
    echo "    -h --help 输出帮助信息"
    exit 255
}
service_cmd=restart
restart_all=1
wait_port_available=1
# 解析命令行参数
for opt in $*; do    
    case "$opt" in
        -a|--all) restart_all=0 ;;
        -w|--wait) wait_port_available=0 ;;
        -s|--stop) service_cmd=stop ;;
        -h|--help) usage;;
        *) 
        echo "无效参数 $opt."
        usage
        ;;
    esac
done

if [ $restart_all -eq 0 ] 
then
    if [ $database_use_local -eq 0 ] || [ $fdevmgr_db_use_local -eq 0 ]
    then
        echo "重启 mysql"
        sudo systemctl $service_cmd mysql || exit 255
        [ $wait_port_available -eq 0 ] &&  wait_port 3306 10 "mysql(3306)"
    fi 
    if [ "$fdevmgr_install" = 'on' ]
    then
        echo "重启 nginx"
        sudo systemctl $service_cmd nginx || exit 255
        [ $wait_port_available -eq 0 ] && wait_port $nginx_port 10 "nginx($nginx_port)"
    fi
    if [ $redis_use_local -eq 0 ]
    then
        echo "重启 redis-server-$redis_port"
        sudo systemctl $service_cmd redis-server-$redis_port || exit 255 
        [ $wait_port_available -eq 0 ] && wait_port $redis_port 10 "redis($redis_port)"
    fi
fi

if [ "$facelog_install"  = 'on' ]
then
    echo "重启 facelog" 
    sudo systemctl $service_cmd facelog  || exit 255
    [ $wait_port_available -eq 0 ] && \
        echo "等待 facelog($facelog_port)服务启动" && \
        wait_port $facelog_port 120 "facelog($facelog_port)"
fi
if [ "$webredis_install" = 'on' ]
then
    echo "重启 webredis"
    sudo systemctl $service_cmd webredis || exit 255
    [ $wait_port_available -eq 0 ] && \
        echo "等待 webredis($webredis_port)服务启动" && \
        wait_port $webredis_port 120 "webredis($webredis_port)"
fi
if [ "$fdevmgr_install"  = 'on' ]
then
    echo "重启 fdevmgr"
    sudo systemctl $service_cmd fdevmgr  || exit 255 
    
    [ $wait_port_available -eq 0 ] && \
        echo "等待 fdevmgr($fdevmgr_port)服务启动，有点慢，请耐心" && \
        wait_port $fdevmgr_port 120 "fdevmgr($fdevmgr_port)"
fi
if [ "$proxy_service_enable" -eq 0 ]
then
    echo "重启 erpc proxy"
    sudo systemctl $service_cmd erpc_proxy  || exit 255 

    [ $wait_port_available -eq 0 ] && \
        echo "等待 erpc_proxy($proxy_port)服务启动" && \
        wait_port $proxy_port 5 "erpc_proxy($proxy_port)"
fi